var onvif = require('onvif');
var Cam = require('onvif').Cam;
var request = require('request');
var express = require('express');
var io = require('socket.io-client');
var app = express();
var dgram = require("dgram");
var boardcast = dgram.createSocket("udp4");
var os = require('os');

var RTMPPROXY_HOSTNAME = '121.42.136.168'
var RTMPPROXY_APP = 'live'

var PROXYPROTOCOL_HOSTNAME = 'localhost'
var PROXYPROTOCOL_PORT = 23583

var WS_HOSTNAME = '121.42.136.168'
var WS_PORT = 3000
var _global_userid = -1;

var address;

app.use(express.static('html'));

app.get('/getid', function (req, res) {
    console.log(_global_userid);
    res.send({
        userid: _global_userid
    });
});

app.get('/login', function (req, res) {
    var username = req.query.username;
    var password = req.query.password;
    console.log('login,username=' + username + ',password=' + password);
    var result;
    if (username == 'root' && password == 'pass') {
        result = {
            result: true,
            userid: 1
        };
    } else {
        result = {
            result: false,
            userid: -1
        };
    }
    _global_userid = result.userid;
    console.log(_global_userid);
    var _userid = result.userid;
    //web socket
    if (_userid > 0) {
        var client = io.connect('ws://' + WS_HOSTNAME + ':' + WS_PORT);
        client.on('connect', function (data) {
            console.log('ws connected!');
            client.emit('login', {
                userid: _userid
            });
            //client.send('hi,there!');
        });

        client.on('play', function (data) {
            var url = data.url;
            request('http://' + PROXYPROTOCOL_HOSTNAME + ':' + PROXYPROTOCOL_PORT + '/play=' + url, function (error, response, body) {
                client.emit('status', {
                    userid: _userid,
                    result: body
                });
            });
        });

        client.on('pause', function (data) {
            var url = data.url;
            request('http://' + PROXYPROTOCOL_HOSTNAME + ':' + PROXYPROTOCOL_PORT + '/pause=' + url, function (error, response, body) {
                client.emit('status', {
                    userid: _userid,
                    result: body
                });
            });
        });
    }
    res.send(result);
});
/*
app.get('/status', function (req, res) {
    var myarray = [];
    for (var i = 0; i < 4; i++) {
        var result = { url: 'rtmp://' + RTMPPROXY_HOSTNAME + '/' + RTMPPROXY_APP + '/ch' + i, speed: GetRandomNum(100, 300) };
        myarray.push(result);
    }
    res.send(myarray);
});
*/

app.get('/status', function (req, res) {
    request('http://' + PROXYPROTOCOL_HOSTNAME + ':' + PROXYPROTOCOL_PORT + '/test=1', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            res.send(body);
        } else {
            res.send('');
        }
    });
});

app.get('/list', function (req, res) {
    request('http://' + PROXYPROTOCOL_HOSTNAME + ':' + PROXYPROTOCOL_PORT + '/list=1', function (error, response, body) {
        //console.log(body);
        //console.log(response.statusCode);
        if (!error && response.statusCode == 200) {
            res.send(body);
        } else {
            res.send('');
        }
    });
});

function GetRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return (Min + Math.round(Rand * Range));
}

app.get('/update', function (req, res) {
    var _json = req.query.json;
    console.log('url=' + _json);
    request('http://' + PROXYPROTOCOL_HOSTNAME + ':' + PROXYPROTOCOL_PORT + '/update=' + _json, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log('start connect:', WS_HOSTNAME);
            request('http://' + WS_HOSTNAME + ':' + WS_PORT + '/update?userlist=' + _json + '&userid=' + _global_userid, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    res.send(body);
                } else {
                    res.send('');
                }
            });
        } else {
            res.send('');
        }
    });
});
/*
app.get('/search', function (req, res) {
    var myarray = [];
    for (var i = 0; i < 4; i++) {
        var result = { in: 'rtsp://192.168.1.' + GetRandomNum(1, 255), hostname: '192.168.1.' + GetRandomNum(1, 255), username: 'admin', password: 'admin', name: 'ch' + i, out: 'rtmp://' + RTMPPROXY_HOSTNAME + '/' + RTMPPROXY_APP + '/ch' + i };
        myarray.push(result);
    }
    res.send(myarray);
});
*/
app.get('/search', function (req, res) {
    onvif.Discovery.probe({ timeout: 1000 }, function (err, cams) {
        if (err) { console.log(err); return; }
        var myarray = [];
        var cameraid = 0;
        if (cams.length == 0) {
            res.send(myarray);
        } else {
            cams.forEach(function (cam) {
                if(cam === undefined){
                    cameraid++;
                    if (cameraid == cams.length)
                        res.send(myarray);
                }
                cam.getStreamUri({ protocol: 'RTSP' }, function (err, stream) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log('rtsp url:' + stream.uri);
                        //generate json "{in:rtsp://xxxx,out:rtmp://xxxxx}" via RTMPPROXY_HOSTNAME and RTMPPROXY_APP
                        var result = {
                            in: stream.uri,
                            hostname: cam.hostname,
                            username: 'admin',
                            password: 'admin',
                            name: 'ch' + cameraid,
                            out: 'rtmp://' + RTMPPROXY_HOSTNAME + '/' + RTMPPROXY_APP + '/ch' + cameraid
                        };
                        myarray.push(result);
                    }
                    cameraid++;
                    if (cameraid == cams.length)
                        res.send(myarray);
                });
            });
        }
    });
});

var server = app.listen(8080, function () {
    var port = server.address().port;
    console.log('listening at port:%s', port);
});

function getHostname() {
    hostName = os.hostname();
    if (os.networkInterfaces().eth0) {
        for (var i = 0; i < os.networkInterfaces().eth0.length; i++) {
            if (os.networkInterfaces().eth0[i].family == 'IPv4') {
                return os.networkInterfaces().eth0[i].address;
            }
        }
    }
    return "0.0.0.0";
}
boardcast.on("error", function (err) {
    console.log("boardcast error:\n" + err.stack);
    boardcast.close();
});
boardcast.on("message", function (msg, rinfo) {
    console.log("boardcast got: " + msg + " from " +
        rinfo.address + ":" + rinfo.port);
    boardcast.send(address, 0, address.length, rinfo.port, rinfo.address, function (err, bytes) {
    });
});
boardcast.on("listening", function () {
    address = getHostname();
    console.log("boardcast listening " +
        address + ":" + 41234);
});
boardcast.bind(41234);
